package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.base.dto.SmsDTO;
import com.atguigu.srb.core.enums.TransTypeEnum;
import com.atguigu.srb.core.hfb.FormHelper;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.mapper.TransFlowMapper;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.bo.TransFlowBO;
import com.atguigu.srb.core.pojo.entity.TransFlow;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import com.atguigu.srb.core.service.UserBindService;
import com.atguigu.srb.core.utils.LendNoUtils;
import com.atguigu.srb.rabbitutil.constant.MQConst;
import com.atguigu.srb.rabbitutil.service.MQService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author tjf
 * @since 2022-01-03
 */
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {
    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private TransFlowMapper transFlowMapper;

    private final TransFlowService transFlowService;

    private final UserBindService userBindService;

    private final MQService mqService;

    public UserAccountServiceImpl(TransFlowService transFlowService, UserBindService userBindService, MQService mqService) {
        this.transFlowService = transFlowService;
        this.userBindService = userBindService;
        this.mqService = mqService;
    }

    @Override
    public String commitCharge(BigDecimal chargeAmt, Long userId) {
        // 获取充值人绑定协议号
        UserInfo userInfo = userInfoMapper.selectById(userId);
        String bindCode = userInfo.getBindCode();

        // 组装自动提交表单的参数
        return FormHelper.buildForm(HfbConst.RECHARGE_URL, new HashMap<String, Object>() {{
            put("agentId", HfbConst.AGENT_ID);
            put("agentBillNo", LendNoUtils.getChargeNo());
            put("bindCode", bindCode);
            put("chargeAmt", chargeAmt);
            put("feeAmt", new BigDecimal("0"));
            put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL);
            put("returnUrl", HfbConst.RECHARGE_RETURN_URL);
            put("timeStamp", RequestHelper.getTimestamp());
            put("sign", RequestHelper.getSign(this));
        }});
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String notify(Map<String, Object> map) {
        // 幂等性判断，判断流水表中是否有记录
        String agentBillNo = (String) map.get("agentBillNo");
        LambdaQueryWrapper<TransFlow> transFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        transFlowLambdaQueryWrapper.eq(TransFlow::getTransNo, agentBillNo);
        boolean exists = transFlowMapper.exists(transFlowLambdaQueryWrapper);
        if (exists) {
            log.warn("幂等性返回");
            return "success";
        }

        // 账户处理
        String bindCode = (String) map.get("bindCode");
        String chargeAmt = (String) map.get("chargeAmt");
        baseMapper.updateAccount(bindCode, new BigDecimal(chargeAmt), null);


        // 记录账户流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(chargeAmt),
                TransTypeEnum.RECHARGE,
                "充值"
        );
        transFlowService.saveTransFlow(transFlowBO);

        // 向消息服务器发消息
        String mobile = userBindService.getMobileByBindCode(bindCode);
        SmsDTO smsDTO = new SmsDTO();
        smsDTO.setMobile(mobile);
        smsDTO.setMessage("充值成功！");
        mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS, MQConst.ROUTING_SMS_ITEM, smsDTO);

        return "success";
    }

    @Override
    public BigDecimal getAccount(Long userId) {
        LambdaQueryWrapper<UserAccount> userAccountLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userAccountLambdaQueryWrapper.select(UserAccount::getAmount)
                .eq(UserAccount::getUserId, userId);
        UserAccount userAccount = baseMapper.selectOne(userAccountLambdaQueryWrapper);
        return userAccount.getAmount();
    }

    @Override
    public String commitWithdraw(BigDecimal fetchAmt, Long userId) {
        BigDecimal amount = getAccount(userId);
        Assert.isTrue(amount.doubleValue() >= fetchAmt.doubleValue(),
                ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);

        // 获取充值人绑定协议号
        UserInfo userInfo = userInfoMapper.selectById(userId);
        String bindCode = userInfo.getBindCode();

        // 组装自动提交表单的参数
        return FormHelper.buildForm(HfbConst.WITHDRAW_URL, new HashMap<String, Object>() {{
            put("agentId", HfbConst.AGENT_ID);
            put("agentBillNo", LendNoUtils.getWithdrawNo());
            put("bindCode", bindCode);
            put("fetchAmt", fetchAmt);
            put("feeAmt", new BigDecimal("0"));
            put("notifyUrl", HfbConst.WITHDRAW_NOTIFY_URL);
            put("returnUrl", HfbConst.WITHDRAW_RETURN_URL);
            put("timeStamp", RequestHelper.getTimestamp());
            put("sign", RequestHelper.getSign(this));
        }});
    }

    @Override
    public String notifyWithdraw(Map<String, Object> map) {
        // 幂等性判断，判断流水表中是否有记录
        String agentBillNo = (String) map.get("agentBillNo");
        LambdaQueryWrapper<TransFlow> transFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        transFlowLambdaQueryWrapper.eq(TransFlow::getTransNo, agentBillNo);
        boolean exists = transFlowMapper.exists(transFlowLambdaQueryWrapper);
        if (exists) {
            log.warn("幂等性返回");
            return "success";
        }

        // 账户处理
        String bindCode = (String) map.get("bindCode");
        String fetchAmt = (String) map.get("fetchAmt");
        baseMapper.updateAccount(bindCode, new BigDecimal(fetchAmt).negate(), null);


        // 记录账户流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(fetchAmt),
                TransTypeEnum.WITHDRAW,
                "提现"
        );
        transFlowService.saveTransFlow(transFlowBO);

        return "success";
    }
}
